<?php
namespace app\common\controller;
// +----------------------------------------------------------------------
// | 后台基础控制器
// +----------------------------------------------------------------------
// | Author:  tiedong
// +----------------------------------------------------------------------
// | Copyright ©2018  https://www.tiedongit.com  All rights reserved.
// +----------------------------------------------------------------------
// | 2018年3月22日
// +----------------------------------------------------------------------

use think\Container;
use think\Controller;
use think\Db;

class AdminBaseController extends Controller
{
    public function __construct()
    {
        $this->_initializeView();
        parent::__construct();

        $this->view  = Container::get('view')->init(
            $this->app['config']->pull('template')
        );
    }

	public function initialize() {
		parent::initialize();
        $site_info = get_option('site_info');

		$session_admin_id = session('ADMIN_ID');
		if (! empty($session_admin_id)) {
		    $groupID = session('admin.group_id');

		    $menu = cache('menu_'.$groupID);
		    if (empty($menu)) {
		        $menu = $this->getAuthMenus($groupID);
		        cache('menu_'.$groupID,$menu,1);
		    }
		    //查询当前链接的规则
		    $pathinfo = $this->request->path();
		    $ruleFind = list_search($menu, array('name'=>$pathinfo));
		    if ($ruleFind) {
		        $rule =$ruleFind['0'];
		    }else{
		        $rule = ['pid'=>0,'id'=>0];
		    }
//		    var_dump($this->request->path());

		    $menu0 = list_search($menu, array('pid'=>0));//一级菜单
		    $menu = list_group_by($menu, 'pid');
		    $admin = session('admin');
		    session('nick_name',$admin['nick_name']);
		    if ($session_admin_id != 1 && $groupID!=1) {//如果不是Administrator，根据权限组ID进行验证
		        if (! $this->checkAuth($admin['group_id'])) {
		            $this->error("您没有访问12权限！");
		        }
		    }

		    $this->assign(['site_info'=>$site_info,'rule'=>$rule,'menu0'=>$menu0,'menu'=>$menu,'admin'=>$admin]);
		} else {
			if ($this->request->isPost()) {
			    header("Location:" . url("admin/public/login"));
// 				$this->error("您还没有登录！", url("admin/public/login"));
			} else {
				header("Location:" . url("admin/public/login"));
				exit();
			}
		}
	}

    public function _initializeView() {
    	$themeBase = 'template/';

    	$frontDefaultTheme = 'backend';

    	$themePath = "{$themeBase}{$frontDefaultTheme}/";

    	config( 'template.view_base', "$themePath" );
    	$tplReplaceStr = [
    		'__PUBLIC__' => "/{$themePath}public",
    	];
    	$tplReplaceStr = array_merge ( config ( 'template.tpl_replace_string' ), $tplReplaceStr );
    	config ( 'template.tpl_replace_string', $tplReplaceStr );
    }

    /**
     * 处理开关操作
     *
     * @author Eric ieyangxiaoguo@126.com
     * @date 2018年03月23日
     */
    public function switchOperate($model)
    {
        if (! is_object($model)) {
            return false;
        }

        if ($this->request->isPost()) {
            $pk = $model->getPk(); // 获取主键名称

            $data[$pk] = $this->request->param('id');
            $field = $this->request->param('field');
            $title = $this->request->param('title');

            $data[$field] = $this->request->param('change');
            $result = $model->allowField(true)->update($data);
            if ($title) {
                if ($data[$field]) {
                    $msg = $title;
                } else {
                    $msg = '取消' . $title;
                }
            } else {
                $msg = '修改';
            }

            $res['code'] = 1;
            $res['msg'] = $msg . '成功！';

            if ($result === false) {
                $res['code'] = 0;
                $res['msg'] = $msg . '失败！';
            }
            return $res;
        } else {
            $res['code'] = 0;
            $res['msg'] = '这是个意外！';
            return $res;
        }
    }

    /**
     * 单元格编辑接口，更新字段值
     * @author Eric ieyangxiaoguo@126.com
     * @date 2018年03月23日
     */
    public function fieldUpdate($model)
    {
        if (! is_object($model)) {
            return false;
        }

        if ($this->request->isPost()) {
            $pk = $model->getPk(); // 获取主键名称

            $data[$pk] = $this->request->param('id');

            $field = $this->request->param('field');
            $value = $this->request->param('value');

            $data[$field] = $value;

            $result = $model->allowField(true)->update($data);

            if ($result === false) {
                $res['code'] = 0;
                $res['msg'] = '出了点问题！';
                return $res;
            }
        } else {
            $res['code'] = 0;
            $res['msg'] = '这是个意外！';
            return $res;
        }
    }

    /**
     * 检查后台用户访问权限
     * @param unknown $groupID
     * @return boolean
     * Date：2018年5月25日下午10:39:05
     * Author: tiedong www.zzuyxg.top
     */
    private function checkAuth($groupID)
    {
        $rule = $this->request->pathinfo();

        $rule_id = Db::name('auth_rule')->where('name',$rule)->value('id');//规则ID

        if ($rule_id) {
            $rules = Db::name('auth_group')->where('id',$groupID)->value('rules');
            $rules = explode(',', $rules);

            if (! in_array($rule_id, $rules)) {
                return false;
            } else {
                return true;
            }
        }else{
            return true;
        }
    }

    /**
     * 获取管理员可操作的栏目
     * @Date：2018年7月27日下午10:08:15
     * @Author: tiedong
     * @param $groupID
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\exception\DbException
     */
    public function getAuthMenus($groupID){
        if ($groupID == 1) {
            $menu = Db::name('auth_rule')->where('status',1)->order('sort asc')->all();
        }else{
            $map['id'] = $groupID;
            $rules = Db::name('auth_group')->where($map)->value('rules');
            $rules = explode(',', $rules);
            $menu = Db::name('auth_rule')->where('id','in',$rules)->where('status',1)->order('sort desc')->all();
        }

        $menu = !empty($menu)? $menu : [];
        return $menu;
    }
}

